# -*- coding: utf-8 -*-
import os
import re
import sys

pkg_root = os.path.realpath(os.path.join(os.path.realpath(__file__),
                                         os.path.pardir,
                                         os.path.pardir))
sys.path.append(pkg_root)

from common.file_utils import *

MD_FILE_PATH_SEARCH_PATTERN = "\d+"
MD_FILE_NAME_PREFIX_PATTERN = "^\d*"


def modify_all_files(root_dir, key, replace):
    def choose_func(file_path, file_name):
        return True if os.path.isfile(file_path) and file_name.endswith(
            ".md") and re.match(MD_FILE_NAME_PREFIX_PATTERN, file_name).group(0) else False

    def sort_key(f):
        return int(re.findall(MD_FILE_PATH_SEARCH_PATTERN, f)[0])

    files = list_all_files(root_dir, choose_func, sort_key)

    for i in files:
        modify_file(i, key, replace)


if __name__ == '__main__':
    if len(sys.argv) > 3:
        print('received arg=' + sys.argv[1] + "," + sys.argv[2] + "," + sys.argv[3])
        modify_all_files(sys.argv[1], sys.argv[2], sys.argv[3])
    else:
        modify_all_files(sys.path[0] + "/", '安卓', ' Android ')
    print('modify done')
